﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CanvasGDI
{
    public partial class CanvasGDI : UserControl, GraphicsFramework.Interface.GraphicsInterface
    {

        //Private variables
        private Graphics.GDI graphics;
        private GraphicsFramework.DrawingLibrary drawings;
        private bool antialias;
        private GraphicsFramework.Enum.EnumDrawingCommands command = GraphicsFramework.Enum.EnumDrawingCommands.SELECT;

        #region Events and Delegates
        
        //Events and Delegates - MouseUpdated
        public delegate void MousePositionUpdatedDelegate(float x, float y);
        public event MousePositionUpdatedDelegate MouseUpdated;

        //Events and Delegates - CommandUpdated
        public delegate void CommandUpdatedDelegate(string command);
        public event CommandUpdatedDelegate CommandUpdated;

        //Events and Delegates - DrawingSelected
        public event GraphicsFramework.DrawingLibrary.DrawingSelectedDelegate DrawingSelected;

        //Events and Delegates - DrawingDeselected
        public event GraphicsFramework.DrawingLibrary.DrawingDeselectedDelegate DrawingDeselected;

        #endregion

        #region Constructors

        public CanvasGDI()
        {
            InitializeComponent();

            //Initialize variables
            graphics = new Graphics.GDI(100, 100, 100, new GraphicsFramework.Entity.Point2F(1, 1));
            drawings = new GraphicsFramework.DrawingLibrary(graphics);

            //Add Events
            drawings.RefreshDrawing += new GraphicsFramework.DrawingLibrary.RefreshDrawingDelegate(RefreshDrawing);
            drawings.CommandUpdated += new GraphicsFramework.DrawingLibrary.CommandUpdatedDelegate(CommandChanged);
            drawings.DrawingSelected += new GraphicsFramework.DrawingLibrary.DrawingSelectedDelegate(DrawingSelectedChanged);
            drawings.DrawingDeselected += new GraphicsFramework.DrawingLibrary.DrawingDeselectedDelegate(DrawingDeselectedChanged);

            //Add Grid
            drawings.AddGrid(new GraphicsFramework.Drawing.Grid.FullGrid());
        }

        #endregion

        #region DrawingLibrary Events

        /// <summary>
        /// Activated where there is a change of command in the drawing library.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="command"></param>
        private void CommandChanged(GraphicsFramework.Enum.EnumDrawingCommands type, string command)
        {
            if (CommandUpdated != null)
                CommandUpdated(command);

            this.command = type;

            if (this.command == GraphicsFramework.Enum.EnumDrawingCommands.SELECT)
            {
                this.Cursor = Cursors.Default;
            }
            else
            {
                this.Cursor = Cursors.Cross;
            }
        }

        /// <summary>
        /// Activated when the graphics library needs to update the canvas.
        /// </summary>
        public void RefreshDrawing()
        {
            if (drawings != null)
                this.Refresh();
        }

        /// <summary>
        /// Activated when drawings are selected in the drawing library.
        /// </summary>
        /// <param name="selected"></param>
        private void DrawingSelectedChanged(GraphicsFramework.Drawing.Base[] selected)
        {
            DrawingSelected(selected);
        }

        private void DrawingDeselectedChanged()
        {
            DrawingDeselected();
        }

        #endregion

        #region Control Events

        private void OnPaint(object sender, PaintEventArgs e)
        {
            if (antialias)
                e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

            graphics.SetGraphics(e.Graphics);
            drawings.OnRender();
        }

        private void OnResize(object sender, EventArgs e)
        {
            if (drawings != null)
                drawings.OnResize(this.Width, this.Height);
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            //If some keycode is not firing this event,
            //kindly override IsInputKey: protected override bool IsInputKey(Keys keyData).
            //Add the keycode/keydata manually.
            drawings.OnKeyDown(graphics.GetKey(e), e.Control, e.Shift, e.Alt);
        }

        private void OnKeyUp(object sender, KeyEventArgs e)
        {
            drawings.OnKeyUp(GraphicsFramework.Enum.EnumKeys.None, false, false, false);
        }

        private void OnMouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Middle)
                this.Cursor = Cursors.SizeAll;

            drawings.OnMouseDown(e.X, e.Y, graphics.GetMouseButton(e));
        }

        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            drawings.OnMouseMove(e.X, e.Y, graphics.GetMouseButton(e));

            //Pass the event.
            if (MouseUpdated != null)
                MouseUpdated(drawings.WorkingCoordinate.X, drawings.WorkingCoordinate.Y);
        }

        private void OnMouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Middle)
            {
                //Change the cursor base on the current command.
                if (this.command == GraphicsFramework.Enum.EnumDrawingCommands.SELECT)
                {
                    this.Cursor = Cursors.Default;
                }
                else if (this.command == GraphicsFramework.Enum.EnumDrawingCommands.PAN)
                {
                    this.Cursor = Cursors.Hand;
                }
                else
                {
                    this.Cursor = Cursors.Cross;
                }
            }
            drawings.OnMouseUp(e.X, e.Y, graphics.GetMouseButton(e));
        }

        protected override void OnMouseWheel(MouseEventArgs e)
        {
            drawings.OnMouseWheel(e.X, e.Y, e.Delta);
        }

        protected override bool IsInputKey(Keys keyData)
        {
            //Some keycode cannot be intercepted by the keydown event.
            //If a certain keycode cannot be intercepted by the keydown event, place here.
            if ((keyData == Keys.Left) ||
                (keyData == Keys.Right) ||
                (keyData == Keys.Up) ||
                (keyData == Keys.Down) ||
                (keyData == Keys.Tab))
            {
                //This will allow keydown event to intercept this keycodes.
                return true;
            }
            else
            {
                return base.IsInputKey(keyData);
            }
        }

        #endregion

        #region GraphicsInterface Members

        public void SelectDrawing()
        {
            drawings.SelectDrawing();
        }

        /// <summary>
        /// Add drawing to the library.
        /// Drawing should come from the GraphicsFramework.Drawing.
        /// Any classes that will be inheriting GraphicsFramework.Drawing.Primitive.BasePrimitive can be added as a drawing.
        /// </summary>
        /// <param name="drawing">Of type GraphicsFramework.Drawing.GraphicBase.</param>
        public void AddDrawing(GraphicsFramework.Drawing.GraphicBase drawing)
        {
            drawings.AddDrawing(drawing);
        }

        /// <summary>
        /// Start drawing using mouse. The drawing that is passed as a parameter will be used as the final drawing.
        /// </summary>
        /// <param name="drawing"></param>
        public void StartDrawing(GraphicsFramework.Drawing.GraphicBase drawing)
        {
            drawings.StartDrawing(drawing);
        }

        public void StartDrawingLine()
        {
            drawings.StartDrawingLine();
        }

        public void StartDrawingPolyline()
        {
            drawings.StartDrawingPolyline();
        }

        public void StartDrawingRectangle()
        {
            drawings.StartDrawingRectangle();
        }

        public void StartDrawingPolygon()
        {
            drawings.StartDrawingPolygon();
        }

        public void ZoomIn()
        {
            drawings.ZoomIn();
        }

        public void ZoomOut()
        {
            drawings.ZoomOut();
        }

        public void ZoomExtent()
        {
            drawings.ZoomExtent();
        }

        public void ZoomWindow()
        {
            drawings.ZoomWindow();
            command = GraphicsFramework.Enum.EnumDrawingCommands.ZOOMWINDOW;
            Cursor = Cursors.Hand;
        }

        public void Pan()
        {
            drawings.Pan();
            command = GraphicsFramework.Enum.EnumDrawingCommands.PAN;
            Cursor = Cursors.Hand;
        }

        public void FlipHorizontal()
        {
            drawings.FlipHorizontal();
        }

        public void FlipVertical()
        {
            drawings.FlipVertical();
        }

        public void RotateLeft()
        {
            drawings.RotateLeft();
        }

        public void RotateRight()
        {
            drawings.RotateRight();
        }

        public void Export(string filename)
        {
            Bitmap file = new Bitmap(graphics.Width, graphics.Height);
            System.Drawing.Graphics export = System.Drawing.Graphics.FromImage(file);

            graphics.SetGraphics(export);
            drawings.OnRender();

            file.Save(filename);
        }

        public GraphicsFramework.Entity.Point2F GridValue
        {
            get { return graphics.GridValue; }
            set
            {
                graphics.GridValue = value;
                RefreshDrawing();
            }
        }

        public void LeftAlign()
        {
            drawings.LeftAlign();
        }

        public void RightAlign()
        {
            drawings.RightAlign();
        }

        public void TopAlign()
        {
            drawings.TopAlign();
        }

        public void BottomAlign()
        {
            drawings.BottomAlign();
        }

        public void HorizontalCenterAlign()
        {
            drawings.HorizontalCenterAlign();
        }

        public void VerticalCenterAlign()
        {
            drawings.VerticalCenterAlign();
        }

        #endregion

        #region Properties

        public bool AntiAlias
        {
            get { return antialias; }
            set { antialias = value; }
        }

        public bool ShowGrid
        {
            get { return drawings.ShowGrid; }
            set { drawings.ShowGrid = value; }
        }

        public bool Snap
        {
            get { return drawings.Snap; }
            set { drawings.Snap = value; }
        }

        #endregion

    }
}
